import re

from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from users.models import User, Address


# 将用户详细信息序列化
class UserSerializer(serializers.ModelSerializer):
    """用户序列化器类"""
    password2 = serializers.CharField(label='重复密码',write_only=True)
    sms_code = serializers.CharField(label='短信验证码',write_only=True)
    allow = serializers.CharField(label='同意协议',write_only=True)
    #添加ｔｏｋｅｎ字段
    token = serializers.CharField(label='JWT token ',read_only=True)
    class Meta:
        model = User
        #　包含ｔｏｋｅｎ字段
        fields = ('id','username','password','mobile','password2','sms_code','allow','token')
        # 可以额外补充参数
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 用户名不能全部是数字
    def validate_username(self, value):
        if re.match(r'^\d+',value):
            raise serializers.ValidationError('用户名不能全部是数字')
        return value

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

        # 手机号是否重复
        count = User.objects.filter(mobile=value).count()
        if count > 0:
            raise serializers.ValidationError('手机号已存在')

        return value

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断两次密码
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        #注意：前端传过来的是str，而redis里面保存的是bytes类型数据
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):
        """
        创建用户
        """
        # 移除数据库模型类中不存在的属性
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # 创建新用户
        user = User.objects.create_user(**validated_data)
        #　添加ＪＷＴ认证机制
        from rest_framework_jwt.settings import api_settings

        # 生成payload的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 生成payload
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)
        #　给用户添加token属性
        user.token = token
        return user
# 将用户详细信息序列化
class UserDetialSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','username','email','email_active','mobile')

# 将邮箱设置序列化
class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','email')

        extra_kwargs = {
            "email":{
                "required":True
            }
        }


    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = email
        instance.save()
        #　发邮件进行验证
        # itsdangerous对user_id进行加密
        # 验证链接：http://www.meiduo.site:8080/success_verify_email.html?<user_id>
        # 如果直接将用户的id放在验证链接中，肯呢个会发生恶意请求
        # 将用户的信息进行加密，然后把加密之后的内容放在验证链接中
        # 验证链接：http://www.meiduo.site:8080/success_verify_email.html?<token=user_id>
        verify_url = instance.generate_verify_email_url()

        #　发送邮件
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email,verify_url)
        return instance


#　地址信息的序列化器
class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)

# 定义用户浏览器序列化器类
class BrowseHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品ID')
    def validated_sku_id(self,value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return value
    def create(self, validated_data):
        """redis中存储登录用户的浏览记录"""
        # 获取redis 链接对象
        redis__conn = get_redis_connection('histories')
        # 获取用户的对象
        user = self.context['request'].user
        # 拼接key
        history_key = 'history_%s' % user.id
        # 去重：如果商品已经被浏览，需要将商品id先从list列表移除
        sku_id = validated_data['sku_id']
        redis__conn.lrem(history_key,0,sku_id)
        #保存有序：最新浏览的商品id加到列表的最左侧
        redis__conn.lpush(history_key,sku_id)
        # 截取：只保留最新几个浏览商品
        redis__conn.ltrim(history_key,0,4)

        return validated_data


class SKUSerializer(serializers.ModelSerializer):
    """sku商品序列化器类"""
    class Meta:
        model = SKU
        fields = ('id','name','price','default_image_url','comments')